package edu.yctc.origin.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

@WebFilter(urlPatterns = "/*", filterName = "CharacterEncodingFilter")
public class CharacterEncodingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest)request;
        HttpServletResponse servletResponse = (HttpServletResponse)response;
        servletRequest.setCharacterEncoding("UTF-8");
        servletResponse.setContentType("UTF-8");
        CharacterRequest characterRequest = new CharacterRequest(servletRequest);
        chain.doFilter(characterRequest, servletResponse);
    }

    /**
     * @className CharacterRequest
     * @description 针对GET请求, 改变request的状态
     * @author zyj
     * @date 2019年12月23日
     *
     */
    class CharacterRequest extends HttpServletRequestWrapper {
        private HttpServletRequest request;

        public CharacterRequest(HttpServletRequest request) {
            super(request);
            this.request = request;
        }

        // 重写getParamter()方法
        public String getParameter(String name) {
            // 调用被包装对象的getParameter()方法，获得请求参数
            String value = super.getParameter(name);
            if (value == null)
                return null;
            // 判断请求方式
            String method = super.getMethod();
            if ("get".equalsIgnoreCase(method)) {
                try {
                    value = new String(value.getBytes("iso8859-1"), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            }
            // 解决乱码后返回结果
            return value;
        }
    }

}
